import time
import requests
import re
import configparser
from tqdm import tqdm
import string

#抖音分享视频链接视频下载

def truncate_before_hash(s):
    index = s.find('#')
    if index != -1:
        return s[:index]
    return s


def remove_illegal_chars(title):
    # 允许的字符包括字母、数字、中文、常见符号
    valid_chars = "-_.() %s%s\u4e00-\u9fff" % (string.ascii_letters, string.digits)
    pattern = re.compile(f'[^{valid_chars}]')
    return pattern.sub('', title)


def get_url(default_video_path):
    url_pattern = r'(https?://[^\s]+)'
    input_url = input("输入需要解析的链接\n")
    match_url = re.search(url_pattern, input_url)
    if match_url is None:
        print("链接解析失败")
        return
    print("视频链接解析中")
    get_video(match_url.group(1), default_video_path)


def get_video(video_url, default_video_path):
    sess = requests.session()
    headers = {
        'user-agent': 'Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36',
        'referer': 'https://www.douyin.com/?is_from_mobile_home=1&recommend=1'
    }
    html_text = sess.get(video_url, headers=headers).text
    pattern = r'"play_addr":\{"uri":"([^"]+)"'
    pattern2 = r'"desc":"([^"]+)"'
    match = re.search(pattern, html_text)
    matchtitle = re.search(pattern2, html_text)
    if matchtitle is None:
        print('标题获取失败')
        return
    title = truncate_before_hash(matchtitle.group(1))
    title = remove_illegal_chars(title)
    if match:
        print("视频链接解析成功，视频即将开始下载。。")
        uri_value = match.group(1)
        print("视频ID：" + uri_value)
        video_url = 'https://www.douyin.com/aweme/v1/play/?video_id=' + uri_value
        resp3 = sess.get(video_url, headers=headers, stream=True)
        if resp3.status_code == 200:
            total_size = int(resp3.headers.get('content-length', 0))
            with open(default_video_path+'\\' + title + '.mp4', 'wb') as f:
                with tqdm(total=total_size, unit='B', unit_scale=True, desc=title) as pbar:
                    for chunk in resp3.iter_content(chunk_size=1024):
                        if chunk:
                            f.write(chunk)
                            pbar.update(len(chunk))
            print("视频保存成功！")
            print("下载完成，5秒后关闭程序")
            time.sleep(5)
        else:
            print(f"请求视频失败，状态码: {resp3.status_code}")
    else:
        print("未找到匹配的uri值")


if __name__ == "__main__":
    config = configparser.ConfigParser()
    config.read('config.ini')
    try:
        default_video_path = config.get('Paths', 'default_video_path')
    except (configparser.NoSectionError, configparser.NoOptionError):
        print("在config.ini文件中未找到default_video_path配置，请检查文件。")
    else:
        get_url(default_video_path)
